home *** CD-ROM | disk | FTP | other *** search
/ Aminet 40 / Aminet 40 (2000)(Schatztruhe)[!][Dec 2000].iso / Aminet / dev / lang / Python16.lha / Python-1.6 / Lib / Python1.6 / os.py < prev    next >
Encoding:
Python Source  |  2000-09-13  |  14.5 KB  |  466 lines

  1. """OS routines for Mac, DOS, NT, or Posix depending on what system we're on.
  2.  
  3. This exports:
  4.   - all functions from posix, nt, dos, os2, mac, or ce, e.g. unlink, stat, etc.
  5.   - os.path is one of the modules posixpath, ntpath, macpath, or dospath
  6.   - os.name is 'posix', 'nt', 'dos', 'os2', 'mac', or 'ce'
  7.   - os.curdir is a string representing the current directory ('.' or ':')
  8.   - os.pardir is a string representing the parent directory ('..' or '::')
  9.   - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')
  10.   - os.altsep is the alternate pathname separator (None or '/')
  11.   - os.pathsep is the component separator used in $PATH etc
  12.   - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
  13.   - os.defpath is the default search path for executables
  14.  
  15. Programs that import and use 'os' stand a better chance of being
  16. portable between different platforms.  Of course, they must then
  17. only use functions that are defined by all platforms (e.g., unlink
  18. and opendir), and leave all pathname manipulation to os.path
  19. (e.g., split and join).
  20. """
  21.  
  22. import sys
  23.  
  24. _names = sys.builtin_module_names
  25.  
  26. altsep = None
  27.  
  28. if 'posix' in _names:
  29.     name = 'posix'
  30.     linesep = '\n'
  31.     curdir = '.'; pardir = '..'; sep = '/'; pathsep = ':'
  32.     defpath = ':/bin:/usr/bin'
  33.     from posix import *
  34.     try:
  35.         from posix import _exit
  36.     except ImportError:
  37.         pass
  38.     import posixpath
  39.     path = posixpath
  40.     del posixpath
  41. elif 'amiga' in _names:
  42.     name = 'amiga'
  43.     linesep = '\n'
  44.     curdir = ''; pardir = '/'; sep = '/'; pathsep = ';'
  45.     defpath = 'C:'
  46.     from amiga import *
  47.     try:
  48.         from amiga import _exit
  49.     except ImportError:
  50.         pass
  51.     import amigapath
  52.     path = amigapath
  53.     del amigapath
  54. elif 'nt' in _names:
  55.     name = 'nt'
  56.     linesep = '\r\n'
  57.     curdir = '.'; pardir = '..'; sep = '\\'; pathsep = ';'
  58.     defpath = '.;C:\\bin'
  59.     from nt import *
  60.     for i in ['_exit']:
  61.         try:
  62.             exec "from nt import " + i
  63.         except ImportError:
  64.             pass
  65.     import ntpath
  66.     path = ntpath
  67.     del ntpath
  68. elif 'dos' in _names:
  69.     name = 'dos'
  70.     linesep = '\r\n'
  71.     curdir = '.'; pardir = '..'; sep = '\\'; pathsep = ';'
  72.     defpath = '.;C:\\bin'
  73.     from dos import *
  74.     try:
  75.         from dos import _exit
  76.     except ImportError:
  77.         pass
  78.     import dospath
  79.     path = dospath
  80.     del dospath
  81. elif 'os2' in _names:
  82.     name = 'os2'
  83.     linesep = '\r\n'
  84.     curdir = '.'; pardir = '..'; sep = '\\'; pathsep = ';'
  85.     defpath = '.;C:\\bin'
  86.     from os2 import *
  87.     try:
  88.         from os2 import _exit
  89.     except ImportError:
  90.         pass
  91.     import ntpath
  92.     path = ntpath
  93.     del ntpath
  94. elif 'mac' in _names:
  95.     name = 'mac'
  96.     linesep = '\r'
  97.     curdir = ':'; pardir = '::'; sep = ':'; pathsep = '\n'
  98.     defpath = ':'
  99.     from mac import *
  100.     try:
  101.         from mac import _exit
  102.     except ImportError:
  103.         pass
  104.     import macpath
  105.     path = macpath
  106.     del macpath
  107. elif 'ce' in _names:
  108.     name = 'ce'
  109.     linesep = '\r\n'
  110.     curdir = '.'; pardir = '..'; sep = '\\'; pathsep = ';'
  111.     defpath = '\\Windows'
  112.     from ce import *
  113.     for i in ['_exit']:
  114.         try:
  115.             exec "from ce import " + i
  116.         except ImportError:
  117.             pass
  118.     # We can use the standard Windows path.
  119.     import ntpath
  120.     path = ntpath
  121.     del ntpath
  122. else:
  123.     raise ImportError, 'no os specific module found'
  124.  
  125. del _names
  126.  
  127. sys.modules['os.path'] = path
  128.  
  129. # Super directory utilities.
  130. # (Inspired by Eric Raymond; the doc strings are mostly his)
  131.  
  132. def makedirs(name, mode=0777):
  133.     """makedirs(path [, mode=0777]) -> None
  134.  
  135.     Super-mkdir; create a leaf directory and all intermediate ones.
  136.     Works like mkdir, except that any intermediate path segment (not
  137.     just the rightmost) will be created if it does not exist.  This is
  138.     recursive.
  139.  
  140.     """
  141.     head, tail = path.split(name)
  142.     if head and tail and not path.exists(head):
  143.         makedirs(head, mode)
  144.     mkdir(name, mode)
  145.  
  146. def removedirs(name):
  147.     """removedirs(path) -> None
  148.  
  149.     Super-rmdir; remove a leaf directory and empty all intermediate
  150.     ones.  Works like rmdir except that, if the leaf directory is
  151.     successfully removed, directories corresponding to rightmost path
  152.     segments will be pruned way until either the whole path is
  153.     consumed or an error occurs.  Errors during this latter phase are
  154.     ignored -- they generally mean that a directory was not empty.
  155.  
  156.     """
  157.     rmdir(name)
  158.     head, tail = path.split(name)
  159.     while head and tail:
  160.         try:
  161.             rmdir(head)
  162.         except error:
  163.             break
  164.         head, tail = path.split(head)
  165.  
  166. def renames(old, new):
  167.     """renames(old, new) -> None
  168.  
  169.     Super-rename; create directories as necessary and delete any left
  170.     empty.  Works like rename, except creation of any intermediate
  171.     directories needed to make the new pathname good is attempted
  172.     first.  After the rename, directories corresponding to rightmost
  173.     path segments of the old name will be pruned way until either the
  174.     whole path is consumed or a nonempty directory is found.
  175.  
  176.     Note: this function can fail with the new directory structure made
  177.     if you lack permissions needed to unlink the leaf directory or
  178.     file.
  179.  
  180.     """
  181.     head, tail = path.split(new)
  182.     if head and tail and not path.exists(head):
  183.         makedirs(head)
  184.     rename(old, new)
  185.     head, tail = path.split(old)
  186.     if head and tail:
  187.         try:
  188.             removedirs(head)
  189.         except error:
  190.             pass
  191.  
  192. # Make sure os.environ exists, at least
  193. try:
  194.     environ
  195. except NameError:
  196.     environ = {}
  197.  
  198. def execl(file, *args):
  199.     """execl(file, *args)
  200.  
  201.     Execute the executable file with argument list args, replacing the
  202.     current process. """
  203.     execv(file, args)
  204.  
  205. def execle(file, *args):
  206.     """execle(file, *args, env)
  207.  
  208.     Execute the executable file with argument list args and
  209.     environment env, replacing the current process. """
  210.     env = args[-1]
  211.     execve(file, args[:-1], env)
  212.  
  213. def execlp(file, *args):
  214.     """execlp(file, *args)
  215.  
  216.     Execute the executable file (which is searched for along $PATH)
  217.     with argument list args, replacing the current process. """
  218.     execvp(file, args)
  219.  
  220. def execlpe(file, *args):
  221.     """execlpe(file, *args, env)
  222.  
  223.     Execute the executable file (which is searched for along $PATH)
  224.     with argument list args and environment env, replacing the current
  225.     process. """    
  226.     env = args[-1]
  227.     execvpe(file, args[:-1], env)
  228.  
  229. def execvp(file, args):
  230.     """execp(file, args)
  231.  
  232.     Execute the executable file (which is searched for along $PATH)
  233.     with argument list args, replacing the current process.
  234.     args may be a list or tupe of strings. """
  235.     _execvpe(file, args)
  236.  
  237. def execvpe(file, args, env):
  238.     """execv(file, args, env)
  239.  
  240.     Execute the executable file (which is searched for along $PATH)
  241.     with argument list args and environment env , replacing the
  242.     current process.
  243.     args may be a list or tupe of strings. """    
  244.     _execvpe(file, args, env)
  245.  
  246. _notfound = None
  247. def _execvpe(file, args, env=None):
  248.     if env is not None:
  249.         func = execve
  250.         argrest = (args, env)
  251.     else:
  252.         func = execv
  253.         argrest = (args,)
  254.         env = environ
  255.     global _notfound
  256.     head, tail = path.split(file)
  257.     if head:
  258.         apply(func, (file,) + argrest)
  259.         return
  260.     if env.has_key('PATH'):
  261.         envpath = env['PATH']
  262.     else:
  263.         envpath = defpath
  264.     PATH = envpath.split(pathsep)
  265.     if not _notfound:
  266.         import tempfile
  267.         # Exec a file that is guaranteed not to exist
  268.         try: execv(tempfile.mktemp(), ('blah',))
  269.         except error, _notfound: pass
  270.     exc, arg = error, _notfound
  271.     for dir in PATH:
  272.         fullname = path.join(dir, file)
  273.         try:
  274.             apply(func, (fullname,) + argrest)
  275.         except error, (errno, msg):
  276.             if errno != arg[0]:
  277.                 exc, arg = error, (errno, msg)
  278.     raise exc, arg
  279.  
  280. # Change environ to automatically call putenv() if it exists
  281. try:
  282.     # This will fail if there's no putenv
  283.     putenv
  284. except NameError:
  285.     pass
  286. else:
  287.     import UserDict
  288.  
  289.     if name in ('os2', 'nt', 'dos'):  # Where Env Var Names Must Be UPPERCASE
  290.         # But we store them as upper case
  291.         class _Environ(UserDict.UserDict):
  292.             def __init__(self, environ):
  293.                 UserDict.UserDict.__init__(self)
  294.                 data = self.data
  295.                 for k, v in environ.items():
  296.                     data[k.upper()] = v
  297.             def __setitem__(self, key, item):
  298.                 putenv(key, item)
  299.                 self.data[key.upper()] = item
  300.             def __getitem__(self, key):
  301.                 return self.data[key.upper()]
  302.             def __delitem__(self, key):
  303.                 del self.data[key.upper()]
  304.             def has_key(self, key):
  305.                 return self.data.has_key(key.upper())
  306.             def get(self, key, failobj=None):
  307.                 return self.data.get(key.upper(), failobj)
  308.             def update(self, dict):
  309.                 for k, v in dict.items():
  310.                     self[k] = v
  311.  
  312.     else:  # Where Env Var Names Can Be Mixed Case
  313.         class _Environ(UserDict.UserDict):
  314.             def __init__(self, environ):
  315.                 UserDict.UserDict.__init__(self)
  316.                 self.data = environ
  317.             def __setitem__(self, key, item):
  318.                 putenv(key, item)
  319.                 self.data[key] = item
  320.             def update(self, dict):
  321.                 for k, v in dict.items():
  322.                     self[k] = v
  323.  
  324.     environ = _Environ(environ)
  325.  
  326. def getenv(key, default=None):
  327.     """Get an environment variable, return None if it doesn't exist.
  328.  
  329.     The optional second argument can specify an alternative default."""
  330.     return environ.get(key, default)
  331.  
  332. def _exists(name):
  333.     try:
  334.         eval(name)
  335.         return 1
  336.     except NameError:
  337.         return 0
  338.  
  339. # Supply spawn*() (probably only for Unix)
  340. if _exists("fork") and not _exists("spawnv") and _exists("execv"):
  341.  
  342.     P_WAIT = 0
  343.     P_NOWAIT = P_NOWAITO = 1
  344.  
  345.     # XXX Should we support P_DETACH?  I suppose it could fork()**2
  346.     # and close the std I/O streams.  Also, P_OVERLAY is the same
  347.     # as execv*()?
  348.  
  349.     def _spawnvef(mode, file, args, env, func):
  350.         # Internal helper; func is the exec*() function to use
  351.         pid = fork()
  352.         if not pid:
  353.             # Child
  354.             try:
  355.                 if env is None:
  356.                     func(file, args)
  357.                 else:
  358.                     func(file, args, env)
  359.             except:
  360.                 _exit(127)
  361.         else:
  362.             # Parent
  363.             if mode == P_NOWAIT:
  364.                 return pid # Caller is responsible for waiting!
  365.             while 1:
  366.                 wpid, sts = waitpid(pid, 0)
  367.                 if WIFSTOPPED(sts):
  368.                     continue
  369.                 elif WIFSIGNALED(sts):
  370.                     return -WTERMSIG(sts)
  371.                 elif WIFEXITED(sts):
  372.                     return WEXITSTATUS(sts)
  373.                 else:
  374.                     raise error, "Not stopped, signaled or exited???"
  375.  
  376.     def spawnv(mode, file, args):
  377.         """spawnv(mode, file, args) -> integer
  378.  
  379. Execute file with arguments from args in a subprocess.
  380. If mode == P_NOWAIT return the pid of the process.
  381. If mode == P_WAIT return the process's exit code if it exits normally;
  382. otherwise return -SIG, where SIG is the signal that killed it. """   
  383.         return _spawnvef(mode, file, args, None, execv)
  384.  
  385.     def spawnve(mode, file, args, env):
  386.         """spawnve(mode, file, args, env) -> integer
  387.  
  388. Execute file with arguments from args in a subprocess with the
  389. specified environment.
  390. If mode == P_NOWAIT return the pid of the process.
  391. If mode == P_WAIT return the process's exit code if it exits normally;
  392. otherwise return -SIG, where SIG is the signal that killed it. """
  393.         return _spawnvef(mode, file, args, env, execve)
  394.  
  395.     # Note: spawnvp[e] is't currently supported on Windows
  396.  
  397.     def spawnvp(mode, file, args):
  398.         """spawnvp(mode, file, args) -> integer
  399.  
  400. Execute file (which is looked for along $PATH) with arguments from
  401. args in a subprocess.
  402. If mode == P_NOWAIT return the pid of the process.
  403. If mode == P_WAIT return the process's exit code if it exits normally;
  404. otherwise return -SIG, where SIG is the signal that killed it. """
  405.         return _spawnvef(mode, file, args, None, execvp)
  406.  
  407.     def spawnvpe(mode, file, args, env):
  408.         """spawnvpe(mode, file, args, env) -> integer
  409.  
  410. Execute file (which is looked for along $PATH) with arguments from
  411. args in a subprocess with the supplied environment.
  412. If mode == P_NOWAIT return the pid of the process.
  413. If mode == P_WAIT return the process's exit code if it exits normally;
  414. otherwise return -SIG, where SIG is the signal that killed it. """
  415.         return _spawnvef(mode, file, args, env, execvpe)
  416.  
  417. if _exists("spawnv"):
  418.     # These aren't supplied by the basic Windows code
  419.     # but can be easily implemented in Python
  420.  
  421.     def spawnl(mode, file, *args):
  422.         """spawnl(mode, file, *args) -> integer
  423.  
  424. Execute file with arguments from args in a subprocess.
  425. If mode == P_NOWAIT return the pid of the process.
  426. If mode == P_WAIT return the process's exit code if it exits normally;
  427. otherwise return -SIG, where SIG is the signal that killed it. """
  428.         return spawnv(mode, file, args)
  429.  
  430.     def spawnle(mode, file, *args):
  431.         """spawnle(mode, file, *args, env) -> integer
  432.  
  433. Execute file with arguments from args in a subprocess with the
  434. supplied environment.
  435. If mode == P_NOWAIT return the pid of the process.
  436. If mode == P_WAIT return the process's exit code if it exits normally;
  437. otherwise return -SIG, where SIG is the signal that killed it. """
  438.         env = args[-1]
  439.         return spawnve(mode, file, args[:-1], env)
  440.  
  441. if _exists("spawnvp"):
  442.     # At the moment, Windows doesn't implement spawnvp[e],
  443.     # so it won't have spawnlp[e] either.
  444.     def spawnlp(mode, file, *args):
  445.         """spawnlp(mode, file, *args, env) -> integer
  446.  
  447. Execute file (which is looked for along $PATH) with arguments from
  448. args in a subprocess with the supplied environment.
  449. If mode == P_NOWAIT return the pid of the process.
  450. If mode == P_WAIT return the process's exit code if it exits normally;
  451. otherwise return -SIG, where SIG is the signal that killed it. """
  452.         return spawnvp(mode, file, args)
  453.  
  454.     def spawnlpe(mode, file, *args):
  455.         """spawnlpe(mode, file, *args, env) -> integer
  456.  
  457. Execute file (which is looked for along $PATH) with arguments from
  458. args in a subprocess with the supplied environment.
  459. If mode == P_NOWAIT return the pid of the process.
  460. If mode == P_WAIT return the process's exit code if it exits normally;
  461. otherwise return -SIG, where SIG is the signal that killed it. """
  462.         env = args[-1]
  463.         return spawnvpe(mode, file, args[:-1], env)
  464.  
  465.  
  466.